package controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

/**
 * @Author:YuhuaZhang
 * @Description
 * @Date:Created in 20:10 2021/11/1
 * @Modified By:
 */
@WebServlet(name = "UploadController", value = "/uploadController")
@MultipartConfig(maxFileSize = 1024 * 1024 * 100, maxRequestSize = 1024 * 1024 * 200)
public class UploadController extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String method = request.getParameter("method");
        switch (method) {
            case "upload":
                this.upload(request, response);
                break;
        }
    }

    private void upload(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //设置乱码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        //通过getpart方法获取文件组件
        Part file = request.getPart("file");
        //获取上传文件保存的真实路径
        String uploadPath = request.getServletContext().getRealPath("/WEB-INF/upload");
        System.out.println("真实路径为：" + uploadPath);
        //创建文件夹对象
        File file1 = new File(uploadPath);
        //如果文件夹不存在，则新建
        if (!file1.exists()) {
            file1.mkdirs();
        }
        //如果上传的文件不是空，进行保存
        if (file != null) {
            file.write(uploadPath + File.separator + file.getSubmittedFileName());
        }
        response.getWriter().println("上传成功！" + file.getSubmittedFileName());
    }

}
